package com.maker.generator.utils;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerTemplateUtil {
	private static Logger log = LoggerFactory.getLogger(FreeMarkerTemplateUtil.class);
    private FreeMarkerTemplateUtil(){
    	
    }

    /**
     * 适用于模板为字符串
     * @param templateContent
     * @param paraMap
     * @return
     */
    public static String templateParser(String templateContent,Map<String, String> paraMap) {
        try {
            StringReader reader = new StringReader(templateContent);
            Template template;
            template = new Template("", reader, null);
            StringWriter out = new StringWriter();

            if (paraMap != null) {
                template.process(paraMap, out);
                String result = out.toString();
                if (log.isDebugEnabled()) {
                    log.debug("template content is:[" + result + "]");
                }
                return result;
            } else {
                return templateContent;
            }
        } catch (Exception e) {
            log.error(e.toString());
            log.error("templateContent = " + templateContent + "\ncontent = "+ paraMap);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 适用于模板保存在本地目录
     * @param paramMap
     * @param templateLoadingDir
     * @param templateFilePath
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    public static String processTemplate( Map< String, Object > paramMap,String templateLoadingDir, String templateFilePath ) throws IOException,
            TemplateException {
        if ( StringUtils.isBlank( templateLoadingDir ) ) {
            throw new TemplateException( "模板文件目录为空", Environment.getCurrentEnvironment( ) );
        }
        else if ( StringUtils.isBlank( templateFilePath ) ) {
            throw new TemplateException( "模板路径为空", Environment.getCurrentEnvironment( ) );
        }
        Configuration cfg = new Configuration( );
        cfg.setDirectoryForTemplateLoading( new File( templateLoadingDir ) );
        cfg.setDefaultEncoding( CharEncoding.UTF_8 );
        Template template = cfg.getTemplate( templateFilePath );

        if ( paramMap == null || paramMap.isEmpty( ) )
        {
            return template.toString( );
        }
        return StringUtils.trimToEmpty( FreeMarkerTemplateUtils.processTemplateIntoString(template, paramMap ) );
    }
}
